package mensa.upb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class XmlDownloader {
	public static final String TAG = "XmlDownloader";
	public static final String PATH = "/sdcard/Mensa";
	Context context;

	public XmlDownloader(Context context) {
		this.context = context;
	}

	public void downloadXml(String url) {
		Log.d(TAG, "Beginning download");

		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}

		if (mExternalStorageWriteable) {
			// Gibt es den Ordner bereits?
			boolean dirExists = new File(PATH).exists();
			// Wenn nicht - erstellen
			if (!dirExists) {
				dirExists = new File(PATH).mkdir();
			}
			// Wenn es den Ordner gibt
			if (dirExists) {
				String filename = PATH + "/" + getFilename(url);
				File file = new File(filename);
				try {
					HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
					FileOutputStream fileOutput;
					fileOutput = new FileOutputStream(file);
					InputStream inputStream = urlConnection.getInputStream();
					int totalSize = urlConnection.getContentLength();
					int downloadedSize = 0;
					byte[] buffer = new byte[1024];
					int bufferLength = 0;
					while ((bufferLength = inputStream.read(buffer)) > 0) {
						fileOutput.write(buffer, 0, bufferLength);
						downloadedSize += bufferLength;
					}
					fileOutput.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private String getFilename(String url) {
		int index = url.lastIndexOf("/");
		return url.substring(index + 1, url.length());
	}
}
